import { computed, inject, reactive } from 'vue'
import { WidgetType, SignData, SignType, Viewer } from '@/types'
import { Widget } from '@/models'
import { PopoverState } from '@/components/contract/useWidgetPopover'

/** 切换签章 */
export default function useChangeSign(popover: PopoverState) {
  /** 合同控件 */
  const viewer = inject('Viewer') as Viewer

  return reactive({
    /** 选择的印章列表 */
    data: computed(() => {
      const { seals, signatures } = viewer
      return popover.widget?.type === WidgetType.SEAL ? seals : signatures
    }),

    /** 选择的印章类型 */
    type: computed(() => (popover.widget?.type === WidgetType.SEAL ? SignType.SEAL : SignType.SIGNATURE) as SignType),

    /** 切换签章 */
    async change(sign: SignData) {
      const widget = popover.widget as Widget
      const options = viewer.signOptions
      const changedWidgets: Widget[] = []

      if (!widget) return

      await viewer.beforeSignChange?.(widget, sign)

      /** 如果开启签章全局切换，则应用当前章到其他可加盖控件 */
      if (options.signGlobal) {
        viewer.widgets
          .filter(
            item =>
              item.type === widget.type &&
              item.isUse &&
              (options.signChangeable ? options.signChangeable(item) : true) &&
              item.sign.id !== sign.id &&
              (!item.assignedSignId || item.assignedSignId === sign.id)
          )
          .forEach(item => {
            item.sign = sign
            changedWidgets.push(item)
          })
      } else {
        // 单个替换
        if (widget.sign.id !== sign.id) {
          // 关联控件
          ;[...widget.linkWidgets, widget].forEach(w => {
            w.sign = sign
            changedWidgets.push(w)
          })
        }
      }

      viewer.$emit('sign-change', widget, sign, options.signGlobal, changedWidgets)
    }
  })
}
